/*
 * MainFrame.java
 *
 * Created on 2007. május 6., 13:03
 */

package fmglemmings;
import java.io.File;
import java.util.TimerTask;
import javax.swing.*;

/**
 *
 * @author  jeneizs
 */
public class MainFrame extends javax.swing.JFrame {
	
	private java.util.Timer refresher;
	private java.util.Timer loop;
        private boolean loaded = false;
        private boolean paused = false;
	protected GameField gf;
	private File chosenFile = null;
	private int choosenLemming = 0;
	private GamePanel gp;
	private static final int GUI_REFRESH = 250;
	private static final int GAME_REFRESH = 1000;
	private static final int MAX_LATE = 5;
	
	public void StartRefreshTimer(){
		if (refresher != null){
			return;
		}
		refresher = new java.util.Timer();
		refresher.schedule(
			new TimerTask(){
			public void run(){
				if ( System.currentTimeMillis() - scheduledExecutionTime() > MAX_LATE ) {
					return;
				}
                                if(loaded)
                                {
                                    lBlocker.setText(Integer.toString(gf.getblocker()));
                                    lFlying.setText(Integer.toString(gf.getflying()));
                                    lBuilder.setText(Integer.toString(gf.getbuilder()));
                                    lBomber.setText(Integer.toString(gf.getbomb()));
                                    lDigger.setText(Integer.toString(gf.getdigger()));
                                    jLabel1.setText("Célba ért: " + Integer.toString(gf.getnumberOfWinners()));
                                    gp.gamerender();
                                }
				repaint();
			}
		},0,GUI_REFRESH);
	}
	public void StartGameLoop(){
		if (loop != null){
			return;
		}
		loop = new java.util.Timer();
		loop.schedule(
			new TimerTask(){
			public void run(){
				if ( System.currentTimeMillis() - scheduledExecutionTime() > MAX_LATE ) {
					return;
				}
				if ((!(paused)) && (loaded)) {
					try{
						gf.input("tik");
						gp.gamerender();
					} catch (GameOverException e) {
							jOptionPane1.showMessageDialog(null, "A játéknak vége. A pontszám: " + credits(), "Vége", jOptionPane1.INFORMATION_MESSAGE);
							paused = true;
						}
				}
			}
		},0,GAME_REFRESH);
	}
        
	/** Creates new form MainFrame */
	public MainFrame() {
		gf = new GameField();
		initComponents();
		StartRefreshTimer();
                StartGameLoop();
		gp  = new GamePanel(gf);
		pGameF.add(gp);
	}
        
        private int credits()
        {
            
            return (10*gf.getnumberOfWinners()+gf.getflying()+gf.getdigger()+gf.getbuilder()+gf.getbomb()+gf.getblocker());
        }
	
	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
        private void initComponents() {
                jFileChooser1 = new javax.swing.JFileChooser();
                jOptionPane1 = new javax.swing.JOptionPane();
                pGameF = new javax.swing.JPanel();
                pButtons = new javax.swing.JPanel();
                bReload = new javax.swing.JButton();
                bEnd = new javax.swing.JButton();
                bBomb = new javax.swing.JButton();
                bBlocker = new javax.swing.JButton();
                bDigger = new javax.swing.JButton();
                bBuilder = new javax.swing.JButton();
                bFlying = new javax.swing.JButton();
                lBlocker = new javax.swing.JLabel();
                lFlying = new javax.swing.JLabel();
                lBuilder = new javax.swing.JLabel();
                lBomber = new javax.swing.JLabel();
                lDigger = new javax.swing.JLabel();
                jLabel1 = new javax.swing.JLabel();
                bPause = new javax.swing.JButton();
                jMenuBar = new javax.swing.JMenuBar();
                jMenu1 = new javax.swing.JMenu();
                mUj = new javax.swing.JMenuItem();
                mExit = new javax.swing.JMenuItem();

                jFileChooser1.setCurrentDirectory(null);
                jFileChooser1.setDialogTitle("P\u00e1lya megnyit\u00e1sa");
                jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                jFileChooser1ActionPerformed(evt);
                        }
                });

                setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
                setTitle("FMG-Lemmings");
                setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
                setResizable(false);
                pGameF.setLayout(new java.awt.GridLayout(1, 0));

                pGameF.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
                pGameF.setMaximumSize(new java.awt.Dimension(750, 500));
                pGameF.setMinimumSize(new java.awt.Dimension(750, 500));
                pGameF.setPreferredSize(new java.awt.Dimension(750, 500));
                pGameF.addMouseListener(new java.awt.event.MouseAdapter() {
                        public void mouseClicked(java.awt.event.MouseEvent evt) {
                                pGameFMouseClicked(evt);
                        }
                });

                pButtons.setBorder(javax.swing.BorderFactory.createEtchedBorder());
                bReload.setText("P\u00e1lya \u00fajra");
                bReload.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bReloadActionPerformed(evt);
                        }
                });

                bEnd.setText("J\u00e1t\u00e9k v\u00e9ge");
                bEnd.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bEndActionPerformed(evt);
                        }
                });

                bBomb.setText("Robban\u00f3");
                bBomb.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bBombActionPerformed(evt);
                        }
                });

                bBlocker.setText("Blokkol\u00f3");
                bBlocker.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bBlockerActionPerformed(evt);
                        }
                });

                bDigger.setText("\u00c1s\u00f3");
                bDigger.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bDiggerActionPerformed(evt);
                        }
                });

                bBuilder.setText("\u00c9p\u00edt\u0151");
                bBuilder.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bBuilderActionPerformed(evt);
                        }
                });

                bFlying.setText("Rep\u00fcl\u0151");
                bFlying.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bFlyingActionPerformed(evt);
                        }
                });

                lBlocker.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                lBlocker.setText(Integer.toString(gf.getblocker()));

                lFlying.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                lFlying.setText(Integer.toString(gf.getflying()));

                lBuilder.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                lBuilder.setText(Integer.toString(gf.getbuilder()));

                lBomber.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                lBomber.setText(Integer.toString(gf.getbomb()));

                lDigger.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                lDigger.setText(Integer.toString(gf.getdigger()));

                jLabel1.setText("Célba ért: " + Integer.toString(gf.getnumberOfWinners()));

                bPause.setText("Pause");
                bPause.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                bPauseActionPerformed(evt);
                        }
                });

                org.jdesktop.layout.GroupLayout pButtonsLayout = new org.jdesktop.layout.GroupLayout(pButtons);
                pButtons.setLayout(pButtonsLayout);
                pButtonsLayout.setHorizontalGroup(
                        pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(pButtonsLayout.createSequentialGroup()
                                .addContainerGap()
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                        .add(bReload, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(bEnd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 135, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(bPause))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                        .add(lBlocker, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(bBlocker, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 99, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(12, 12, 12)
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(lFlying, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
                                        .add(bFlying, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                        .add(lBuilder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(bBuilder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                        .add(lBomber, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(bBomb))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                        .add(lDigger, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(bDigger, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 83, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap())
                );

                pButtonsLayout.linkSize(new java.awt.Component[] {bBlocker, bBomb, bBuilder, bDigger, bFlying}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

                pButtonsLayout.linkSize(new java.awt.Component[] {bEnd, bPause}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

                pButtonsLayout.setVerticalGroup(
                        pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(pButtonsLayout.createSequentialGroup()
                                .addContainerGap()
                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(pButtonsLayout.createSequentialGroup()
                                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                                        .add(bBomb)
                                                        .add(bBuilder)
                                                        .add(bFlying)
                                                        .add(bBlocker)
                                                        .add(bDigger))
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                                        .add(lBlocker)
                                                        .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                                                .add(lFlying)
                                                                .add(lBomber)
                                                                .add(lDigger)
                                                                .add(lBuilder))))
                                        .add(pButtonsLayout.createSequentialGroup()
                                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                                        .add(jLabel1)
                                                        .add(bReload))
                                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                                .add(pButtonsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                                        .add(bPause)
                                                        .add(bEnd))))
                                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                );

                jMenu1.setText("F\u00e1jl");
                jMenu1.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                jMenu1ActionPerformed(evt);
                        }
                });

                mUj.setText("\u00daj j\u00e1t\u00e9k...");
                mUj.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                mUjActionPerformed(evt);
                        }
                });

                jMenu1.add(mUj);

                mExit.setText("Kil\u00e9p");
                mExit.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                mExitActionPerformed(evt);
                        }
                });

                jMenu1.add(mExit);

                jMenuBar.add(jMenu1);

                setJMenuBar(jMenuBar);

                org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
                getContentPane().setLayout(layout);
                layout.setHorizontalGroup(
                        layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                                .addContainerGap()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, pButtons, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, pGameF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 750, Short.MAX_VALUE))
                                .addContainerGap())
                );
                layout.setVerticalGroup(
                        layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                                .addContainerGap()
                                .add(pGameF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 500, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(pButtons, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                );
                pack();
        }// </editor-fold>//GEN-END:initComponents

        private void bPauseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPauseActionPerformed
            if(loaded) paused = !paused;
        }//GEN-LAST:event_bPauseActionPerformed
	
    private void bEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bEndActionPerformed
	    try {
                    paused = true;
		    gf.input("stop");
	    } catch (GameOverException e) {
		    gp.gamerender();
		    jOptionPane1.showMessageDialog(null, "A játéknak vége. A pontszám: " + credits(), "Vége", jOptionPane1.INFORMATION_MESSAGE);
	    }
    }//GEN-LAST:event_bEndActionPerformed
    
    private void pGameFMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pGameFMouseClicked
	    int x, y;
	    String cmd = "swap ";
	    x = evt.getX() / 25;
	    y = evt.getY() / 25;
	    if(choosenLemming > 0) {
		    cmd += x;
		    cmd += " ";
		    cmd += y;
		    cmd += " ";
		    switch (choosenLemming) {
			    case 1: cmd += "BlockerLemming"; break;
			    case 2: cmd += "FlyingLemming"; break;
			    case 3: cmd += "BuilderLemming"; break;
			    case 4: cmd += "BomberLemming"; break;
			    case 5: cmd += "DiggerLemming"; break;
		    }
		    try{
                        gf.input(cmd);
                    }
                    catch (Exception e) {System.out.println(e.toString());}
	    }
	    
    }//GEN-LAST:event_pGameFMouseClicked
    
    private void bDiggerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDiggerActionPerformed
	    choosenLemming = 5;
    }//GEN-LAST:event_bDiggerActionPerformed
    
    private void bBombActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBombActionPerformed
	    choosenLemming = 4;
    }//GEN-LAST:event_bBombActionPerformed
    
    private void bBuilderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBuilderActionPerformed
	    choosenLemming = 3;
    }//GEN-LAST:event_bBuilderActionPerformed
    
    private void bFlyingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bFlyingActionPerformed
	    choosenLemming = 2;
    }//GEN-LAST:event_bFlyingActionPerformed
    
    private void bBlockerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBlockerActionPerformed
	    choosenLemming = 1;
    }//GEN-LAST:event_bBlockerActionPerformed
    
    private void bReloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReloadActionPerformed
            try
            {
                if(chosenFile != null)
                {
                    gf = new GameField(chosenFile.toString());
                    gp.setGF(gf);
                    gp.gamerender();
                    loaded = true;
                    paused = false;
                }
	    } catch (Exception nfe) {jOptionPane1.showMessageDialog(null, "Hibás fájlformátum!", "Hiba", jOptionPane1.ERROR_MESSAGE);}
    }//GEN-LAST:event_bReloadActionPerformed
        
    private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser1ActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jFileChooser1ActionPerformed
    
    private void mExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mExitActionPerformed
        if(jOptionPane1.YES_OPTION == jOptionPane1.showConfirmDialog(null, "Biztos, hogy kilépsz?", "Biztos?", jOptionPane1.YES_NO_OPTION)) System.exit(0);
    }//GEN-LAST:event_mExitActionPerformed
    
    private void mUjActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mUjActionPerformed
	    int returnVal = jFileChooser1.showOpenDialog(this);
	    if(returnVal == jFileChooser1.APPROVE_OPTION) chosenFile =jFileChooser1.getSelectedFile();
	    try 
            {
                if(chosenFile != null) 
                {
                    gf = new GameField(chosenFile.toString());
                    gp.setGF(gf);
                    gp.gamerender();
                    loaded = true;
                    paused = false;
                }
	    } catch (Exception nfe) {jOptionPane1.showMessageDialog(null, "Hibás fájlformátum!", "Hiba", jOptionPane1.ERROR_MESSAGE);}
    }//GEN-LAST:event_mUjActionPerformed
    
    
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jMenu1ActionPerformed
    
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JButton bBlocker;
        private javax.swing.JButton bBomb;
        private javax.swing.JButton bBuilder;
        private javax.swing.JButton bDigger;
        private javax.swing.JButton bEnd;
        private javax.swing.JButton bFlying;
        private javax.swing.JButton bPause;
        private javax.swing.JButton bReload;
        private javax.swing.JFileChooser jFileChooser1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenuBar jMenuBar;
        private javax.swing.JOptionPane jOptionPane1;
        private javax.swing.JLabel lBlocker;
        private javax.swing.JLabel lBomber;
        private javax.swing.JLabel lBuilder;
        private javax.swing.JLabel lDigger;
        private javax.swing.JLabel lFlying;
        private javax.swing.JMenuItem mExit;
        private javax.swing.JMenuItem mUj;
        private javax.swing.JPanel pButtons;
        private javax.swing.JPanel pGameF;
        // End of variables declaration//GEN-END:variables
	
}
